//
//  MoyaApi.swift
//  QMXK
//
//  Created by jenkin on 2018/12/3.
//  Copyright © 2018年 jenkin. All rights reserved.
//

import Foundation
import Moya

// MARK: - Provider setup
private func JSONResponseDataFormatter(_ data: Data) -> Data {
    do {
        let dataAsJSON = try JSONSerialization.jsonObject(with: data)
        let prettyData =  try JSONSerialization.data(withJSONObject: dataAsJSON, options: .prettyPrinted)
        return prettyData
    } catch {
        return data // fallback to original data if it can't be serialized.
    }
}

let moyaProvider = MoyaProvider<MoyaApi>(plugins: [NetworkLoggerPlugin(verbose: true, responseDataFormatter: JSONResponseDataFormatter)])

// MARK: - Provider support
private extension String{
    var urlEscaped:String{
        return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
    }
}

public enum MoyaApi{
    case appInit(data:[String:Any])
    case infoList(data:[String:Any])
    case update(data:[String:Any])
    case articleType(data:[String:Any])
    case articleListType(data:[String:Any])
}

////文章列表
//#define Article_List_URL ADDRESS_URL(@"article/index")
////分类列表
//#define Article_Type_URL ADDRESS_URL(@"article/type")

extension MoyaApi: TargetType{
    public var baseURL: URL {
        return URL(string: "https://app.00227.com/api/")!
    }
    
    public var path: String {
        switch self {
        case .appInit:
            return "app/init"
        case .infoList:
            return ""
        case .update:
            return ""
        case .articleType:
            return "article/type"
        case .articleListType:
            return "article/index"
        }
    }
    
    public var method: Moya.Method {
        return .get
    }
    
    public var sampleData: Data {
        return Data(base64Encoded: "just for test")!
    }
    
    public var task: Task {
        var newData:[String:Any]
        switch self {
        case let .appInit(data):
            newData = data
            break;
        case .infoList(let data):
            newData = data
            break;
        case .update(let data):
            newData = data
            break;
        case .articleType(let data):
            newData = data
            break;
        case .articleListType(let data):
            newData = data
            break;
        }
        
        //数据处理
        newData["clientid"] = "319829a1e74eac41d29229056db7e788a736ef075d9906591a5c8b18aed964b1"
        newData["uid"] = "0"
        newData["token"] = ""
        newData["channel"] = "appStore"
        newData["os"] = "2"
        newData["app_version"] = "3.2"
        newData["tmp"] = Date.init().timeIntervalSince1970
        return .requestParameters(parameters: newData, encoding: URLEncoding.default)
    }
    
    public var headers: [String : String]? {
        return ["Content-type" : "application/json"]
    }
}
